/**
 * 
 */
package cn.com.gxetc.assistant.config;

import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.com.gxetc.assistant.utils.JwtUtils;
import me.chanjar.weixin.cp.api.WxCpService;

/**
 * @author yfm
 *
 */

public class SecurityInterceptor implements HandlerInterceptor {

	private WxCpService wxCpService;
	private JwtUtils jwtUtils;

	public SecurityInterceptor(WxCpService wxCpService, JwtUtils jwtUtils) {
		this.wxCpService = wxCpService;
		this.jwtUtils = jwtUtils;
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse arg1, Object arg2) throws Exception {
		String token=request.getHeader("token");
		if(null == token){
			token=getCookieToken(request);
		}
        if(null==token || null==jwtUtils.getClaimByToken(token)){
        	String redirectUrl = URLEncoder.encode("http://assistant.gxetc.com.cn/auth", "utf8");
	    	arg1.sendRedirect(wxCpService.getOauth2Service().buildAuthorizationUrl(redirectUrl,"gxetc"));
	    	return false;
	    }
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse,
			Object paramObject, ModelAndView paramModelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest paramHttpServletRequest,
			HttpServletResponse paramHttpServletResponse, Object paramObject, Exception paramException)
			throws Exception {

	}
	
	private String getCookieToken(HttpServletRequest req){
		Cookie[] cookies=req.getCookies();
		if (null!=cookies && cookies.length>0) {
			for (int i = 0; i < cookies.length; i++) {
				if("token".equals(cookies[i].getName())){
					return cookies[i].getValue();
				}
			}
		}
		return null;
	}

}
